package com.jrx.anytxn.customer.mq;

import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.common.uitl.JsonUtils;
import com.jrx.anytxn.customer.constant.CustomerConstant;
import com.jrx.anytxn.customer.entity.CmCustomerLimitInfo;
import com.jrx.anytxn.customer.entity.CmLimitAdjustLog;
import com.jrx.anytxn.customer.handel.ICustomerLimitInfoHandler;
import com.jrx.anytxn.customer.mapper.base.CmLimitAdjustLogMapper;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.BtLimitAdjustInfo;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.mapper.ext.ExtBtLimitAdjustInfoMapper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 批量调额消费
 *
 * @author : zhenghaopu
 * 2020/1/7
 */
@Service
@RocketMQMessageListener(
        topic = CustomerConstant.MQ_BATCH_LIMIT_ADJUST_TOPIC,
        consumerGroup = CustomerConstant.MQ_BATCH_LIMIT_ADJUST_GROUP,
        consumeThreadMax = 10
)
public class BatchLimitAdjustMqConsumerService implements RocketMQListener<String> {

    private static final Logger logger = LoggerFactory.getLogger(BatchLimitAdjustMqConsumerService.class);

    @Autowired
    private ICustomerLimitInfoHandler customerLimitInfoHandler;

    @Resource
    private CmLimitAdjustLogMapper cmLimitAdjustLogMapper;

    @Resource
    private ExtBtLimitAdjustInfoMapper extBtLimitAdjustInfoMapper;

    @Autowired
    private ISegmentService segmentService;

    @Autowired
    private IOrganizationTableService organizationTableService;

    @Override
    public void onMessage(String jSonMessage) {
        //调额信息实体
        BtLimitAdjustInfo btLimitAdjustInfo;
        try {
            btLimitAdjustInfo = JsonUtils.json2pojo(jSonMessage, BtLimitAdjustInfo.class);
        } catch (Exception e) {
            logger.error("批量调额MQ消费端JSon转换异常", e);
            return;
        }
        //调额原始客户额度信息
        CmCustomerLimitInfo customerLimitInfo = null;
        try{
            //调额
            customerLimitInfo = customerLimitInfoHandler.batchLimitAdjust(btLimitAdjustInfo);
            //构建成功日志
            CmLimitAdjustLog cmLimitAdjustLog = buildCmLimitAdjustLog(btLimitAdjustInfo,CustomerConstant.SUCCESS,
                    "调额成功",customerLimitInfo);
            cmLimitAdjustLogMapper.insertSelective(cmLimitAdjustLog);
            //修改调额信息状态
            btLimitAdjustInfo.setAdjustStatus(Constant.ADJUST_SATTUS_1);
        }catch(Exception e){
            logger.error("批量调额异常", e);
            //修改调额信息状态
            btLimitAdjustInfo.setAdjustStatus(Constant.ADJUST_SATTUS_2);

            String errMsg = e instanceof TxnException ? e.getMessage():"调额失败";
            CmLimitAdjustLog cmLimitAdjustLog = buildCmLimitAdjustLog(btLimitAdjustInfo, CustomerConstant.FAIL,
                        errMsg,customerLimitInfo);

            cmLimitAdjustLogMapper.insertSelective(cmLimitAdjustLog);
        }
        btLimitAdjustInfo.setUpdateBy(Constant.DEFAULT_USER);
        //更新调额信息状态
        extBtLimitAdjustInfoMapper.updateBySeqNoAndTenantIdForBatch(btLimitAdjustInfo);
    }

    private CmLimitAdjustLog buildCmLimitAdjustLog(BtLimitAdjustInfo btLimitAdjustInfo, String result,
                                                   String msg, CmCustomerLimitInfo customerLimitInfo) {
        CmLimitAdjustLog cmLimitAdjustLog = new CmLimitAdjustLog();
        BeanUtils.copyProperties(btLimitAdjustInfo,cmLimitAdjustLog);

        //验证机构是否存在
        PrOrganizationTable organizationTable = null;
        try {
            organizationTable = organizationTableService.findByOrId(btLimitAdjustInfo.getOrganizationId(), btLimitAdjustInfo.getTenantId());
        } catch (TxnBizException e) {
            logger.error("获取机构信息异常");
        }

        try {
            cmLimitAdjustLog.setId(segmentService.getId(Constant.CM_LIMIT_ADJUST_LOG));
        }catch (SegmentException e){
            logger.error("主键生成错误 ");
        }
        cmLimitAdjustLog.setAdjustType(CustomerConstant.ADJUST_TYPE_0);//调额
        cmLimitAdjustLog.setAdjustReason("批量调额");
        cmLimitAdjustLog.setResult(result);
        cmLimitAdjustLog.setDescription(msg);
        cmLimitAdjustLog.setBusinessDate(organizationTable.getNextProcessingDate());//添加业务日期
        if(CustomerConstant.SUCCESS.equals(result)){
            cmLimitAdjustLog.setLimitPermBefore(customerLimitInfo.getLimitPerm());
            cmLimitAdjustLog.setLimitPermAfter(btLimitAdjustInfo.getLimitPerm());
        }
        cmLimitAdjustLog.setRecordVersionNumber(Constant.VERSION_NUMBER);
        return cmLimitAdjustLog;
    }
}
